<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>添加/编辑专辑</title>
    <link rel="stylesheet" href="../res/layui/css/layui.css">
    <style>
        .layui-form-item {
            margin-bottom: 25px;
        }
        .album-cover-preview {
            width: 200px;
            height: 200px;
            border: 1px solid #ddd;
            background-color: #f9f9f9;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            margin-bottom: 10px;
        }
        .album-cover-preview img {
            max-width: 100%;
            max-height: 100%;
        }
        .cover-upload-btn {
            width: 200px;
        }
        .cover-upload-text {
            margin-top: 5px;
            color: #999;
            font-size: 12px;
        }
    </style>
</head>
<body>
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-header">添加/编辑专辑</div>
        <div class="layui-card-body">
            <form class="layui-form" id="albumForm" lay-filter="albumForm">
                <input type="hidden" name="id" id="albumId">
                
                <!-- 专辑封面上传 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">专辑封面:</label>
                    <div class="layui-input-block">
                        <div class="album-cover-preview" id="coverPreview">
                            <img id="ID-upload-demo-img" src="../res/images/default_album.jpg" alt="专辑封面">
                        </div>
                        <button type="button" class="layui-btn layui-btn-normal cover-upload-btn" id="btnMusic">
                            <i class="layui-icon layui-icon-upload"></i> 上传封面
                        </button>
                        <input type="hidden" name="pic" id="coverUrl" value="">
                        <p class="cover-upload-text">支持JPG、PNG格式，建议尺寸300x300像素</p>
                    </div>
                </div>
                
                <!-- 专辑名称 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">专辑名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="name" id="musicname" lay-verify="required" placeholder="请输入专辑名称" autocomplete="off" class="layui-input">
                    </div>
                </div>
                
                <!-- 歌手 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">歌手</label>
                    <div class="layui-input-block">
                        <input type="text" name="singer" id="singerName" lay-verify="required" placeholder="请输入歌手名称" autocomplete="off" class="layui-input">
                    </div>
                </div>
                
                <!-- 唱片公司和发行时间 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">唱片公司:</label>
                    <div class="layui-input-inline">
                        <input class="layui-input" type="text" name="company" id="company" placeholder="请输入唱片公司">
                    </div>
                    <label class="layui-form-label">发行时间:</label>
                    <div class="layui-input-inline">
                        <input class="layui-input" type="text" name="publishTime" id="releasedate">
                    </div>
                </div>
                
                <!-- 状态 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">状态</label>
                    <div class="layui-input-block">
                        <input type="radio" name="status" value="1" title="上架" checked>
                        <input type="radio" name="status" value="0" title="下架">
                    </div>
                </div>
                
                <!-- 提交按钮 -->
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit lay-filter="submitAlbum" id="addMusic">保存专辑</button>
                        <button type="button" class="layui-btn layui-btn-primary" id="backBtn">返回列表</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="../res/layui/layui.js"></script>
<script>
    layui.use(['form', 'layer', 'upload', 'laydate', 'jquery'], function() {
        var form = layui.form;
        var layer = layui.layer;
        var upload = layui.upload;
        var laydate = layui.laydate;
        var $ = layui.jquery;
        
        // 初始化日期选择器
        laydate.render({
            elem: '#releasedate',
            type: 'date',
            format: 'yyyy-MM-dd',
            max: new Date().toISOString().split('T')[0] // 最大日期为今天
        });
        
        // 扩展Date的format方法
        Date.prototype.format = function(fmt) {
            var o = {
                "M+": this.getMonth() + 1,
                "d+": this.getDate(),
                "h+": this.getHours(),
                "m+": this.getMinutes(),
                "s+": this.getSeconds(),
                "q+": Math.floor((this.getMonth() + 3) / 3),
                "S": this.getMilliseconds()
            };
            if(/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            for(var k in o)
                if(new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return fmt;
        };
        
        // 封面上传配置
        upload.render({
            elem: '#btnMusic',
            url: '/file/upload',
            size: 2048, // 最大2MB
            exts: 'jpg|png',
            before: function(obj) {
                // 预读本地文件示例
                obj.preview(function(index, file, result) {
                    $('#ID-upload-demo-img').attr('src', result);
                });
                layer.load(); // 上传loading
            },
            done: function(res) {
                layer.closeAll('loading'); // 关闭loading
                if (res.success) {
                    // 上传成功
                    $('#coverUrl').val(res.data.url);
                    layer.msg('上传成功', {icon: 1});
                } else {
                    // 上传失败
                    layer.msg(res.message || '上传失败', {icon: 5});
                    $('#ID-upload-demo-img').attr('src', '../res/images/default_album.jpg');
                }
            },
            error: function() {
                layer.closeAll('loading'); // 关闭loading
                layer.msg('上传失败，请稍后重试', {icon: 5});
                $('#ID-upload-demo-img').attr('src', '../res/images/default_album.jpg');
            }
        });
        
        // 检查URL中是否有id参数，判断是编辑还是添加
        function checkEditMode() {
            var urlParams = new URLSearchParams(window.location.search);
            var albumId = urlParams.get('id');
            if (albumId) {
                // 编辑模式，加载专辑数据
                $.ajax({
                    url: '/album/details',
                    type: 'GET',
                    data: {id: albumId},
                    success: function(res) {
                        if (res.success) {
                            var album = res.data;
                            // 填充表单数据
                            $('#albumId').val(album.id);
                            $('#musicname').val(album.name);
                            $('#singerName').val(album.singer);
                            $('#company').val(album.company);
                            if (album.publishTime) {
                                var publishDate = new Date(album.publishTime);
                                $('#releasedate').val(publishDate.format('yyyy-MM-dd'));
                            }
                            $(":radio[name='status'][value='" + album.status + "']").prop('checked', true);
                            if (album.pic) {
                                $('#ID-upload-demo-img').attr('src', album.pic);
                                $('#coverUrl').val(album.pic);
                            }
                            // 重新渲染表单
                            form.render();
                        } else {
                            layer.msg(res.message || '获取专辑信息失败', {icon: 5});
                        }
                    },
                    error: function() {
                        layer.msg('网络错误，请稍后重试', {icon: 5});
                    }
                });
            }
        }
        
        // 返回列表按钮点击事件
        $('#backBtn').click(function() {
            window.location.href = 'album-list.html';
        });
        
        // 表单提交
        form.on('submit(submitAlbum)', function(data) {
            // 获取表单数据
            var formData = data.field;
            
            // 验证必填字段
            if (!formData.name || formData.name.trim() === '') {
                layer.msg('专辑名称不能为空', {icon: 5});
                return false;
            }
            if (!formData.singer || formData.singer.trim() === '') {
                layer.msg('歌手不能为空', {icon: 5});
                return false;
            }
            
            // 格式化发布时间
            if (formData.publishTime) {
                formData.publishTime = new Date(formData.publishTime).toISOString();
            }
            
            // 判断是添加还是更新
            var url = formData.id ? '/album/update' : '/album/add';
            
            // 提交数据（使用JSON格式）
            $.ajax({
                url: url,
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function(res) {
                    if (res.success) {
                        layer.msg(formData.id ? '更新成功' : '添加成功', {icon: 1}, function() {
                            window.location.href = 'album-list.html';
                        });
                    } else {
                        layer.msg(res.message || '操作失败', {icon: 5});
                    }
                },
                error: function() {
                    layer.msg('网络错误，请稍后重试', {icon: 5});
                }
            });
            return false; // 阻止表单跳转
        });
        
        // 页面加载时检查编辑模式
        checkEditMode();
        
        // 渲染表单
        form.render();
    });
</script>
</body>
</html>